/*
 * Copyright 2014 NAVER Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ideal.ete.collector.dao.Impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.ideal.hbase.client.HbaseOperations;
import com.ideal.hbase.client.HbaseTemplate;
import com.ideal.hbase.client.core.mapper.RowMapper;
import com.ideal.ete.collector.application.Application;
import com.ideal.ete.collector.dao.ApplicationIndexDao;
import com.ideal.ete.collector.hbase.HBaseTables;

/**
 * @author netspider
 * @author emeroad
 */
@Repository
public class ApplicationIndexDaoImpl implements ApplicationIndexDao {

//    private static HbaseOperations hbaseOperations = new HbaseTemplate();

    @Autowired
    private HbaseOperations hbaseOperations;

    @Autowired
    @Qualifier("applicationNameMapper")
    private RowMapper<List<Application>> applicationNameMapper;

    @Autowired
    @Qualifier("agentIdMapper")
    private RowMapper<List<String>> agentIdMapper;


    @Override
    public List<Application> selectAllApplicationNames() {
        Scan scan = new Scan();
        scan.setCaching(30);
//        HbaseOperations hbaseOperations = HbaseTemplate.INSTANCE;
      
        
        List<List<Application>> results = hbaseOperations.find(HBaseTables.APPLICATION_INDEX, scan, applicationNameMapper);
        List<Application> applications = new ArrayList<>();
        for (List<Application> result : results) {
            applications.addAll(result);
        }
        return applications;
    }
    
    @Override
    public List<String> selectAgentIds(String applicationName) {
        if (applicationName == null) {
            throw new NullPointerException("applicationName must not be null");
        }
        byte[] rowKey = Bytes.toBytes(applicationName);

        Get get = new Get(rowKey);
        get.addFamily(HBaseTables.APPLICATION_INDEX_CF_AGENTS);

        return hbaseOperations.get(HBaseTables.APPLICATION_INDEX, get, agentIdMapper);
    }

}
